package com.back.service.impl;

import com.back.dto.JobDTO;
import com.back.entity.Company;
import com.back.entity.CompanyRecruiter;
import com.back.entity.Job;
import com.back.entity.JobTag;
import com.back.entity.JobTagRelation;
import com.back.entity.JobApplication;
import com.back.mapper.CompanyMapper;
import com.back.mapper.CompanyRecruiterMapper;
import com.back.mapper.JobApplicationMapper;
import com.back.mapper.JobMapper;
import com.back.mapper.JobTagMapper;
import com.back.mapper.JobTagRelationMapper;
import com.back.service.IJobService;
import com.back.vo.CompanyVO;
import com.back.vo.JobListVO;
import com.back.vo.JobVO.JobTagVO;
import com.back.vo.JobVO;
import com.back.vo.RecruiterVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@Service
@Slf4j
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements IJobService {

    @Autowired
    private JobTagMapper jobTagMapper;
    
    @Autowired
    private JobTagRelationMapper jobTagRelationMapper;
    
    @Autowired
    private CompanyMapper companyMapper;
    
    @Autowired
    private CompanyRecruiterMapper companyRecruiterMapper;
    
    @Autowired
    private JobApplicationMapper jobApplicationMapper;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Override
    public IPage<JobListVO> getJobList(Integer page, Integer pageSize, Map<String, Object> params) {
        // 创建分页对象
        Page<Job> jobPage = new Page<>(page, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Job> queryWrapper = new LambdaQueryWrapper<>();
        
        // 默认只显示招聘中的职位
        queryWrapper.eq(Job::getStatus, "active");
        queryWrapper.eq(Job::getDeleted, false);
        
        // 添加搜索条件
        if (params != null) {
            // 关键词搜索
            if (params.containsKey("keyword") && StringUtils.hasText((String) params.get("keyword"))) {
                String keyword = (String) params.get("keyword");
                queryWrapper.and(wrapper -> 
                    wrapper.like(Job::getTitle, keyword)
                           .or()
                           .like(Job::getDescription, keyword)
                );
            }
            
            // 工作地点
            if (params.containsKey("location") && StringUtils.hasText((String) params.get("location"))) {
                queryWrapper.like(Job::getLocation, params.get("location"));
            }
            
            // 职位类别
            if (params.containsKey("category") && StringUtils.hasText((String) params.get("category"))) {
                queryWrapper.eq(Job::getCategory, params.get("category"));
            }
            
            // 薪资范围
            if (params.containsKey("salary") && StringUtils.hasText((String) params.get("salary"))) {
                queryWrapper.like(Job::getSalary, params.get("salary"));
            }
            
            // 经验要求
            if (params.containsKey("experience") && StringUtils.hasText((String) params.get("experience"))) {
                queryWrapper.eq(Job::getExperience, params.get("experience"));
            }
            
            // 学历要求
            if (params.containsKey("education") && StringUtils.hasText((String) params.get("education"))) {
                queryWrapper.eq(Job::getEducation, params.get("education"));
            }
            
            // 公司ID
            if (params.containsKey("companyId") && params.get("companyId") != null) {
                queryWrapper.eq(Job::getCompanyId, params.get("companyId"));
            }
            
            // 职位状态
            if (params.containsKey("status") && StringUtils.hasText((String) params.get("status"))) {
                String status = (String) params.get("status");
                if (status.contains(",")) {
                    List<String> statusList = List.of(status.split(","));
                    queryWrapper.in(Job::getStatus, statusList);
                } else {
                    queryWrapper.eq(Job::getStatus, status);
                }
            }
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Job::getCreateTime);
        
        // 执行分页查询
        IPage<Job> jobIPage = this.page(jobPage, queryWrapper);
        
        // 转换结果
        IPage<JobListVO> resultPage = jobIPage.convert(this::convertToListVO);
        
        return resultPage;
    }
    
    @Override
    public JobVO getJobDetail(Long id) {
        // 获取职位信息
        Job job = this.getById(id);
        if (job == null || job.getDeleted()) {
            return null;
        }
        
        return convertToVO(job);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JobVO createJob(JobDTO jobDTO, Long companyId, Long recruiterId) {
        // 创建职位对象
        Job job = new Job();
        
        // 设置基本信息
        job.setTitle(jobDTO.getTitle());
        job.setCompanyId(companyId);
        job.setRecruiterId(recruiterId);
        job.setCategory(jobDTO.getCategory());
        job.setLocation(jobDTO.getLocation());
        job.setSalary(jobDTO.getSalary());
        job.setEducation(jobDTO.getEducation());
        job.setExperience(jobDTO.getExperience());
        job.setDescription(jobDTO.getDescription());
        job.setBenefits(jobDTO.getBenefits());
        
        // 转换列表为JSON
        try {
            if (jobDTO.getResponsibilities() != null) {
                job.setResponsibilities(objectMapper.writeValueAsString(jobDTO.getResponsibilities()));
            }
            
            if (jobDTO.getSkills() != null) {
                job.setSkills(objectMapper.writeValueAsString(jobDTO.getSkills()));
            }
        } catch (JsonProcessingException e) {
            log.error("JSON转换异常", e);
            throw new RuntimeException("职位信息格式错误");
        }
        
        // 设置初始状态
        job.setStatus("pending");
        job.setViews(0);
        job.setApplications(0);
        job.setDeleted(false);
        
        // 设置时间
        long currentTime = System.currentTimeMillis();
        job.setCreateTime(currentTime);
        job.setUpdateTime(currentTime);
        
        // 保存职位
        this.save(job);
        
        // 保存标签关联
        if (jobDTO.getTags() != null && !jobDTO.getTags().isEmpty()) {
            saveTags(job.getId(), jobDTO.getTags());
        }
        
        // 返回结果
        return convertToVO(job);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateJob(Long id, JobDTO jobDTO, Long companyId) {
        // 获取职位信息
        Job job = this.getById(id);
        if (job == null || job.getDeleted()) {
            return false;
        }
        
        // 验证权限
        if (!job.getCompanyId().equals(companyId)) {
            return false;
        }
        
        // 更新基本信息
        job.setTitle(jobDTO.getTitle());
        job.setCategory(jobDTO.getCategory());
        job.setLocation(jobDTO.getLocation());
        job.setSalary(jobDTO.getSalary());
        job.setEducation(jobDTO.getEducation());
        job.setExperience(jobDTO.getExperience());
        job.setDescription(jobDTO.getDescription());
        job.setBenefits(jobDTO.getBenefits());
        
        // 转换列表为JSON
        try {
            if (jobDTO.getResponsibilities() != null) {
                job.setResponsibilities(objectMapper.writeValueAsString(jobDTO.getResponsibilities()));
            }
            
            if (jobDTO.getSkills() != null) {
                job.setSkills(objectMapper.writeValueAsString(jobDTO.getSkills()));
            }
        } catch (JsonProcessingException e) {
            log.error("JSON转换异常", e);
            throw new RuntimeException("职位信息格式错误");
        }
        
        // 设置更新时间
        job.setUpdateTime(System.currentTimeMillis());
        
        // 更新职位
        this.updateById(job);
        
        // 更新标签关联
        if (jobDTO.getTags() != null) {
            // 删除原有关联
            LambdaQueryWrapper<JobTagRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JobTagRelation::getJobId, id);
            jobTagRelationMapper.delete(wrapper);
            
            // 保存新关联
            if (!jobDTO.getTags().isEmpty()) {
                saveTags(id, jobDTO.getTags());
            }
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteJob(Long id, Long companyId) {
        // 获取职位信息
        Job job = this.getById(id);
        if (job == null || job.getDeleted()) {
            return false;
        }
        
        // 验证权限
        if (!job.getCompanyId().equals(companyId)) {
            return false;
        }
        
        // 逻辑删除
        job.setDeleted(true);
        job.setUpdateTime(System.currentTimeMillis());
        
        return this.updateById(job);
    }
    
    @Override
    public boolean closeJob(Long id, Long companyId) {
        // 获取职位信息
        Job job = this.getById(id);
        if (job == null || job.getDeleted()) {
            return false;
        }
        
        // 验证权限
        if (!job.getCompanyId().equals(companyId)) {
            return false;
        }
        
        // 关闭职位
        job.setStatus("closed");
        job.setUpdateTime(System.currentTimeMillis());
        
        return this.updateById(job);
    }
    
    @Override
    public boolean reopenJob(Long id, Long companyId) {
        // 获取职位信息
        Job job = this.getById(id);
        if (job == null || job.getDeleted()) {
            return false;
        }
        
        // 验证权限
        if (!job.getCompanyId().equals(companyId)) {
            return false;
        }
        
        // 重新开启职位
        job.setStatus("active");
        job.setUpdateTime(System.currentTimeMillis());
        
        return this.updateById(job);
    }
    
    @Override
    public Map<String, Object> getApplicationStatus(Long jobId, Long userId) {
        // 查询申请记录
        LambdaQueryWrapper<JobApplication> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobApplication::getJobId, jobId)
               .eq(JobApplication::getUserId, userId)
               .eq(JobApplication::getDeleted, false);
        
        JobApplication application = jobApplicationMapper.selectOne(wrapper);
        
        Map<String, Object> result = new HashMap<>();
        result.put("jobId", jobId);
        
        if (application != null) {
            result.put("status", application.getStatus());
            result.put("applicationId", application.getId());
            result.put("appliedAt", application.getCreateTime());
        } else {
            result.put("status", null);
        }
        
        return result;
    }
    
    @Override
    public List<JobListVO> getSimilarJobs(Long jobId, Integer limit) {
        if (limit == null || limit <= 0) {
            limit = 5;
        }
        
        // 获取当前职位
        Job job = this.getById(jobId);
        if (job == null || job.getDeleted()) {
            return new ArrayList<>();
        }
        
        // 获取该职位的标签
        List<Long> tagIds = getJobTagIds(jobId);
        
        // 查找具有相同标签的职位
        List<Job> similarJobs = new ArrayList<>();
        if (!tagIds.isEmpty()) {
            // 获取具有相同标签的职位ID
            LambdaQueryWrapper<JobTagRelation> tagWrapper = new LambdaQueryWrapper<>();
            tagWrapper.in(JobTagRelation::getTagId, tagIds)
                     .ne(JobTagRelation::getJobId, jobId);
            
            List<JobTagRelation> relations = jobTagRelationMapper.selectList(tagWrapper);
            
            // 按职位ID分组并计数
            Map<Long, Long> jobCounts = relations.stream()
                .collect(Collectors.groupingBy(JobTagRelation::getJobId, Collectors.counting()));
            
            // 按匹配标签数降序排序
            List<Long> sortedJobIds = jobCounts.entrySet().stream()
                .sorted(Map.Entry.<Long, Long>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
            
            // 获取职位详情
            if (!sortedJobIds.isEmpty()) {
                LambdaQueryWrapper<Job> jobWrapper = new LambdaQueryWrapper<>();
                jobWrapper.in(Job::getId, sortedJobIds)
                         .eq(Job::getStatus, "active")
                         .eq(Job::getDeleted, false)
                         .orderByDesc(Job::getCreateTime);
                
                similarJobs = this.list(jobWrapper);
            }
        }
        
        // 如果相似职位不足，补充同类别职位
        if (similarJobs.size() < limit) {
            LambdaQueryWrapper<Job> categoryWrapper = new LambdaQueryWrapper<>();
            categoryWrapper.eq(Job::getCategory, job.getCategory())
                          .eq(Job::getStatus, "active")
                          .eq(Job::getDeleted, false)
                          .ne(Job::getId, jobId)
                          .orderByDesc(Job::getCreateTime);
            
            // 排除已有的相似职位
            List<Long> existingJobIds = similarJobs.stream()
                .map(Job::getId)
                .collect(Collectors.toList());
            
            if (!existingJobIds.isEmpty()) {
                categoryWrapper.notIn(Job::getId, existingJobIds);
            }
            
            List<Job> categoryJobs = this.list(categoryWrapper);
            
            // 补充到相似职位列表
            int needMore = limit - similarJobs.size();
            if (needMore > 0 && !categoryJobs.isEmpty()) {
                similarJobs.addAll(categoryJobs.subList(0, Math.min(needMore, categoryJobs.size())));
            }
        }
        
        // 限制数量
        if (similarJobs.size() > limit) {
            similarJobs = similarJobs.subList(0, limit);
        }
        
        // 转换为VO
        return similarJobs.stream()
            .map(this::convertToListVO)
            .collect(Collectors.toList());
    }
    
    @Override
    public void incrementJobViews(Long jobId) {
        Job job = this.getById(jobId);
        if (job != null && !job.getDeleted()) {
            job.setViews(job.getViews() + 1);
            this.updateById(job);
        }
    }
    
    @Override
    public boolean markJobNotInterested(Long jobId, Long userId) {
        // 这里可以根据需求实现不感兴趣的记录
        // 实现略，返回成功
        return true;
    }
    
    /**
     * 保存职位标签关联
     */
    private void saveTags(Long jobId, List<Long> tagIds) {
        for (Long tagId : tagIds) {
            JobTagRelation relation = new JobTagRelation();
            relation.setJobId(jobId);
            relation.setTagId(tagId);
            relation.setCreateTime(System.currentTimeMillis());
            relation.setUpdateTime(System.currentTimeMillis());
            jobTagRelationMapper.insert(relation);
        }
    }
    
    /**
     * 获取职位标签ID列表
     */
    private List<Long> getJobTagIds(Long jobId) {
        LambdaQueryWrapper<JobTagRelation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(JobTagRelation::getJobId, jobId);
        
        List<JobTagRelation> relations = jobTagRelationMapper.selectList(wrapper);
        
        return relations.stream()
            .map(JobTagRelation::getTagId)
            .collect(Collectors.toList());
    }
    
    /**
     * 获取职位标签信息
     */
    private List<JobTagVO> getJobTags(Long jobId) {
        List<Long> tagIds = getJobTagIds(jobId);
        
        if (tagIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 查询标签详情
        LambdaQueryWrapper<JobTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(JobTag::getId, tagIds);
        
        List<JobTag> tags = jobTagMapper.selectList(wrapper);
        
        // 转换为VO
        List<JobTagVO> tagVOs = new ArrayList<>();
        for (JobTag tag : tags) {
            JobTagVO tagVO = new JobTagVO();
            tagVO.setId(tag.getId());
            tagVO.setName(tag.getName());
            tagVOs.add(tagVO);
        }
        
        return tagVOs;
    }
    
    /**
     * 将Job转换为JobVO
     */
    private JobVO convertToVO(Job job) {
        if (job == null) {
            return null;
        }
        
        JobVO jobVO = new JobVO();
        BeanUtils.copyProperties(job, jobVO);
        
        // 设置公司信息
        Company company = companyMapper.selectById(job.getCompanyId());
        if (company != null) {
            jobVO.setCompanyName(company.getName());
            jobVO.setCompanyLogo(company.getLogo());
            
            // 设置公司详情
            CompanyVO companyVO = new CompanyVO();
            companyVO.setId(company.getId());
            companyVO.setName(company.getName());
            companyVO.setLogo(company.getLogo());
            companyVO.setIndustry(company.getIndustry());
            companyVO.setSize(company.getSize());
            
            // 此处可以进一步完善公司信息
        }
        
        // 设置招聘者信息
        CompanyRecruiter recruiter = companyRecruiterMapper.selectById(job.getRecruiterId());
        if (recruiter != null) {
            RecruiterVO recruiterVO = new RecruiterVO();
            recruiterVO.setId(recruiter.getId());
            recruiterVO.setName(recruiter.getRealName());
            recruiterVO.setPosition(recruiter.getPosition());
            // 此处可以进一步完善招聘者信息
            
            jobVO.setRecruiter(recruiterVO);
        }
        
        // 转换JSON字符串为对象
        try {
            if (StringUtils.hasText(job.getResponsibilities())) {
                jobVO.setResponsibilities(objectMapper.readValue(job.getResponsibilities(), 
                    new TypeReference<List<String>>() {}));
            }
            
            if (StringUtils.hasText(job.getSkills())) {
                jobVO.setSkills(objectMapper.readValue(job.getSkills(), 
                    new TypeReference<List<String>>() {}));
            }
        } catch (JsonProcessingException e) {
            log.error("JSON解析异常", e);
            jobVO.setResponsibilities(new ArrayList<>());
            jobVO.setSkills(new ArrayList<>());
        }
        
        // 设置标签
        jobVO.setTags(getJobTags(job.getId()));
        
        return jobVO;
    }
    
    /**
     * 将Job转换为JobListVO
     */
    public JobListVO convertToListVO(Job job) {
        if (job == null) {
            return null;
        }
        
        JobListVO listVO = new JobListVO();
        BeanUtils.copyProperties(job, listVO);
        
        // 设置公司信息
        Company company = companyMapper.selectById(job.getCompanyId());
        if (company != null) {
            listVO.setCompanyName(company.getName());
            listVO.setCompanyLogo(company.getLogo());
        }
        
        // 设置标签列表（仅名称）
        List<JobTagVO> tagVOs = getJobTags(job.getId());
        List<String> tagNames = tagVOs.stream()
            .map(JobTagVO::getName)
            .collect(Collectors.toList());
        
        listVO.setTags(tagNames);
        
        return listVO;
    }
}
